import React, { PureComponent } from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {
  Input,
  Button,
  Form,
  Select,
  Card,
  Row,
  Col,
  Icon,
  Modal,
  DatePicker,
  message,
} from 'antd';
import Drawer from 'react-motion-drawer';
import moment from 'moment';

import {
  getDictInformation, //公共信息
  systemConfigPerCerInfoFindListByPercertype,//新增证书-查看证书特殊信息字段
  systemPerCerBaseInfoSave,//新增证书-保存
} from "../../../services/api";

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
// const RadioGroup = Radio.Group;
const { TextArea } = Input;
const dateFormat = 'YYYY/MM/DD';
message.config({
  top: 100,
  right: 5,
  duration: 2,
});

// @connect(state => ({ profile: state.profile }))
@Form.create()

// 新增证书-抽屉
export default class NewCertificateDrawer extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      newCertificateOpen: this.props.visiable,//抽屉
      perCerType: [],//证书类型
      perCerlevel: [],//证书等级
      certificateType: '1',
      specialFields: [],
      perId: '',
    };

  }
  /******************************生命周期******************************/

  componentDidMount = () => {
    this.getAllType();//获取所有类型
    // this.getSpecialFields();//特殊字段
    console.log("新增证书-this", this);
  };
  componentWillReceiveProps(props) {
    this.setState({ newCertificateOpen: props.visiable, perId: props.perId }, () => {
      console.log('perId值', this.state.perId);
    });
  }
  /******************************ajax请求******************************/
  //获得公共信息
  getAllType = () => {
    getDictInformation({ codeTypes: [' perCerType', ' perCerlevel'] }).then((res) => {
      console.log('证书字典表-res:', res);
      //判断获取数据是否为空
      if (res.data) {
        const allTypeData = res.data;
        this.setState({
          perCerType: allTypeData.perCerType,
          perCerlevel: allTypeData.perCerlevel,
        });
      }
    });
  };

  //新增证书-查看证书特殊信息字段
  getSpecialFields = () => {
    const perCerType = this.state.certificateType;
    systemConfigPerCerInfoFindListByPercertype({ perCerType }).then((res) => {
      console.log('新增特殊字段-res:', res);
      if (res.data) {
        this.setState({
          specialFields: res.data,
        });
      }
      console.log("特殊字段数组", this.state.specialFields);
    }, (err) => {
      console.log('新增特殊字段-错误信息', err);
    });
  };


  /******************************相关事件******************************/
  changeCertificateType = (value) => {
    console.log("证书类型切换：", value);
    if (value) {
      this.setState({
        specialFields: [],
      });
      systemConfigPerCerInfoFindListByPercertype({ perCerType: value }).then((res) => {
        console.log('新增特殊字段-res:', res);
        if (res.data) {
          this.setState({
            specialFields: res.data,
          });
        }
        console.log("特殊字段数组", this.state.specialFields);
      }, (err) => {
        console.log('新增特殊字段-错误信息', err);
      });
    }
  };

  showFixedFields = () => {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <FormItem
          {...formItemLayout}
          label="证书编号"
        >
          {getFieldDecorator('cerNo', {
            rules: [{
              required: true, message: '请输入证书编号',
            }, {
              pattern: /^([A-Za-z0-9])|(.){6,20}$/, message: '格式错误！',
            }],
          })(
            <Input placeholder="请输入" maxLength="20" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="发证机关:"
        >
          {getFieldDecorator('licenceOrg', {
            rules: [{
              required: true, message: '请输入发证机关',
            }
              //   , {
              //   validator: this.checkPhone
              // }
            ],
          })(
            <Input placeholder="请输入" maxLength="20" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label=" 发证机关编号"
        >
          {getFieldDecorator('licenceOrgNo', {
            rules: [{
              required: true, message: '请输入发证机关编号',
            }, {
              pattern: /^([A-Za-z0-9])|(.){6,20}$/, message: '格式错误！',
            }],
          })(
            <Input placeholder="请输入" maxLength="20" />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="发证日期"
        >
          {getFieldDecorator('licenceDate', {
            rules: [{
              type: 'object', required: true, message: '请选择证书发证日期',
            }],
          })(
            <DatePicker format={dateFormat} placeholder="请选择证书发证日期" style={{ width: '100 % ' }} />
          )}
        </FormItem>
      </div>
    );
  }

  showSpecialFields = () => {
    const arr = this.state.specialFields.map((value, index) => {
      return (
        <div key={index}>
          {this.renderMap(value.fieldType, value.fieldName, value.fieldCode, value.isRequired)}
        </div>
      );
    });
    return arr;
  }

  renderMap = (fieldType, fieldName, fieldCode, isRequired) => {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;

    if (fieldType === '1') {
      return (
        <FormItem
          {...formItemLayout}
          label={fieldName}
        >
          {getFieldDecorator(`${fieldCode}`, {
            rules: [{
              required: isRequired, message: `请输入${fieldName}`,
            }],
          })(
            <Input placeholder="请输入" />
          )}
        </FormItem>
      );
    } else if (fieldType === '4') {
      return (
        <FormItem
          {...formItemLayout}
          label={fieldName}
        >
          {getFieldDecorator(`${fieldCode}`, {
            rules: [{
              required: isRequired, message: `请选择${fieldName}`,
            }],
          })(
            <Select placeholder="请选择" className="sls-style">
              <Option value=" ">请选择</Option>
              {this.renderCertificateLevel()}
            </Select>
          )}
        </FormItem>
      );
    } else if (fieldType === '9') {
      return (
        <FormItem
          {...formItemLayout}
          label={fieldName}
        >
          {getFieldDecorator(`${fieldCode}`, {
            rules: [{
              required: isRequired, message: `请选择${fieldName}`,
            }],
          })(
            <DatePicker format={dateFormat} placeholder="请选择" style={{ width: '100%' }} />
          )}
        </FormItem>
      );
    }
  };

  //表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log("specialFields-提交时候0特殊数组", this.state.specialFields);
      if (!err) {
        console.log("values", values);
        console.log("新增-提交-this", this);

        const { perId } = this.state.perId;//人员ID
        console.log('perId的值', this.state.perId);
        // const perId = '402871315091947520';//人员ID
        console.log("人员id是否正确---perId", perId);
        let list = [];
        console.log("specialFields-特殊数组", this.state.specialFields);
        if (values) {
          for (let [k, v] of Object.entries(values)) {
            this.state.specialFields.map((val) => {
              if (val.fieldCode === k) {
                console.log("进入");

                if (typeof v === 'object') {
                  console.log("values[key]", k);
                  v = moment(v['_d']).format(dateFormat);
                  console.log("values[key]-vvv", v);
                  val.fieldValue = v;
                } else {
                  val.fieldValue = v;
                }
              }
              return true;
            });
          }
          list = this.state.specialFields;
          // list.push(
          //   {
          //     fieldCode: 'perCerLevel',
          //     fieldValue: values.perCerLevel ? values.perCerLevel : '',//证书等级
          //   },
          //   {
          //     fieldCode: 'trainStartDate',
          //     fieldValue: values.trainStartDate ? values.trainStartDate.format('YYYY-MM-DD') : '',//培训开始日期
          //   },
          //   {
          //     fieldCode: 'trainEndDate',
          //     fieldValue: values.trainEndDate ? values.trainEndDate.format('YYYY-MM-DD') : '',//培训结束日期
          //   },
          //   {
          //     fieldCode: 'trainOrganName',
          //     fieldValue: values.trainOrganName ? values.trainOrganName : '',//培训单位
          //   },
          //   {
          //     fieldCode: 'pressIndoCardNumber ',
          //     fieldValue: values.pressIndoCardNumber ? values.pressIndoCardNumber : '',//"十指指纹按印卡号"
          //   },
          //   {
          //     fieldCode: 'certificateStartDate',
          //     fieldValue: values.certificateStartDate ? values.certificateStartDate.format('YYYY-MM-DD') : '',//有效期开始日期
          //   },
          //   {
          //     fieldCode: 'certificateEndDate',
          //     fieldValue: values.certificateEndDate ? values.certificateEndDate.format('YYYY-MM-DD') : '',//有效期结束日期
          //   },
          //   {
          //     fieldCode: 'gunProofCode',
          //     fieldValue: values.gunProofCode ? values.gunProofCode : '',//""持枪证枪型代码""
          //   },
          // );
        }
        console.log("list数组", list);
        list = JSON.stringify(list);
        console.log("list数组-字符串", list);

        const obj = {
          perId,
          perCerType: values.perCerType ? values.perCerType : '',//证书类型
          cerNo: values.cerNo ? values.cerNo : '',//证书编号
          licenceOrg: values.licenceOrg ? values.licenceOrg : '',//发证机关
          licenceOrgNo: values.licenceOrgNo ? values.licenceOrgNo : '',//发证机关编号
          licenceDate: values.licenceDate ? values.licenceDate.format('YYYY-MM-DD') : '',//发证日期
          //perCerLevel: values.perCerLevel ? values.perCerLevel : '',//证书等级
          list,
        };
        console.log("obj", obj);
        obj.perId = this.state.perId;
        systemPerCerBaseInfoSave(obj).then((res) => {
          console.log("成功信息-新增证书：", res);
          message.success("保存成功！");
          this.setState({ newCertificateOpen: false });
          this.props.refreshList();
          const { setFieldsValue } = this.props.form;
          setFieldsValue({
            perCerType: '',//证书类型
            cerNo: '',//证书编号
            licenceOrg: '',//发证机关
            licenceOrgNo: '',//发证机关编号
            licenceDate: '',//发证日期
          });
          const listArray = JSON.parse(list);
          console.log("listArray数组", listArray);
          const newListArray = [];
          for (const value of listArray) {
            console.log(value.fieldCode);
            newListArray.push(value.fieldCode);
          }
          console.log("newListArray", newListArray);
          for (let i = 0; i < newListArray.length; i++) {
            console.log("最后的value", newListArray[i]);
            setFieldsValue({
              [newListArray[i]]: '',
            });
          }
        }, (error) => {
          message.error(error);
          console.log("错误信息-新增证书：", error);
        });
      }
    });
  }
  //证书类型
  renderCertificateType = () => {
    return this.state.perCerType.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //证书等级
  renderCertificateLevel = () => {
    return this.state.perCerlevel.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  /******************************render******************************/

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;

    return (
      <Box>
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.newCertificateOpen}
          noTouchClose
          width={600}
          zIndex={2}
          className="drawer-box"
          onChange={(newCertificateOpen) => {
            this.props.onChange(newCertificateOpen);
            this.setState({ newCertificateOpen });
          }}
        >
          <div className="drawer">
            <div className="drawer-header">新增证书</div>
            <div className="drawer-content">
              <Form onSubmit={this.handleSubmit}>
                <FormItem
                  {...formItemLayout}
                  label="证书类型"
                >
                  {getFieldDecorator('perCerType', {
                    rules: [
                      { required: true, message: '请选择证书类型!' },
                    ],
                  })(
                    <Select onChange={this.changeCertificateType} placeholder="请选择证书类型" className="sls-style">
                      {this.renderCertificateType()}
                    </Select>
                  )}
                </FormItem>
                {this.showFixedFields()}
                {this.showSpecialFields()}
              </Form>
            </div>
            <div className="drawer-footer">
              <Button onClick={() => this.setState({ newCertificateOpen: false })}>取消</Button>
              <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>确认新增</Button>
            </div>
          </div>
        </Drawer>
      </Box>
    );
  }
}

/************************样式************************/

const Box = style.div`{
  .drawer-content{
    margin-top:28px;
  }
  .ant-calendar-picker{
    width:100%;
  }
}`;
